function quality_index = counterbalance_quality(sequence, counterbalanceLevel)

wordCount = zeros(2^counterbalanceLevel,1);
wordLen = counterbalanceLevel;
number_of_label_to_wrap_around = wordLen - 1;
newsequence = [sequence sequence(1:number_of_label_to_wrap_around)];

N = length(sequence);

for i=1:N
    thisWord = newsequence(i:(i + wordLen-1));
    binaryWord = num2str(thisWord);
    binaryWord(binaryWord==' ') = '';
    wordCount(1 + bin2dec(binaryWord)) = wordCount(1 + bin2dec(binaryWord)) + 1;
end

expected_number_of_each_word = N / 2^counterbalanceLevel;

deviations_from_ideal = wordCount - expected_number_of_each_word * ones(2^counterbalanceLevel,1);

quality_index = 1 - sum(abs(deviations_from_ideal))/(2*N*(2^counterbalanceLevel - 1)/(2^counterbalanceLevel));